<?php
require_once('Extension/Controller/Action.php');

class Admin_UserController extends Extension_Controller_Action
{
    public function indexAction()
    {
        if (!Zend_Auth::getInstance()->hasIdentity()) {
            $this->_forward('login');
        } else {
            $this->_redirect('/admin');
        }
    }

    public function loginAction()
    {
        $request = $this->getRequest();
        
        $formLogin = $this->getHelper('Form')->getFormLogin();

        if ($request->isPost()) {

            $posts = $request->getPost();

            if ($formLogin->isValid($posts)) {

                //$valuesUnfiltered = $formLogin->getUnfilteredValues();
                //$this->authLogin($valuesUnfiltered);

                $values = $formLogin->getValues();
                $this->authLogin($values);

            } else {
                $errors = $formLogin->getMessages();
                foreach ($errors as $name => $m) {
                    $message .= nl2br($name . ' : ' . implode(PHP_EOL, $m) . PHP_EOL);
                }
                $flashMessenger = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');
                $flashMessenger->setNamespace('login')->addMessage($message);
            }
        }

        if (Zend_Auth::getInstance()->hasIdentity()) {
            $this->_forword('index');
        } else {
            $this->view->formLogin = $formLogin;
        }
    }

    public function logoutAction()
    {
        $namespaces = Zend::initConfig('Session')->namespace;
        Extension_Session::namespaceUnset($namespaces->auth->dbTable);
        Extension_Session::namespaceUnset($namespaces->acl);

        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();
        $this->_forward('login');
    }

    public static function authLogin($data)
    {
        $message = '';
        $namespace = 'login';

        $authAdapterDbTable = Zend_Registry::get('authAdapterDbTable');
        $authAdapterDbTable->setIdentity($data['userLogin'])->setCredential($data['userPass']);

        $auth = Zend_Auth::getInstance();
        $result = $auth->authenticate($authAdapterDbTable);

        if ($result->isValid()) {
            if ($data['remember']) {
                Extension_Session::rememberMe();
            }
            $data = $authAdapterDbTable->getResultRowObject(null, 'user_pass');
            $auth->getStorage()->write($data);
            $namespace = 'index';
        }

        $message = implode('<br />', $result->getMessages() );

        $flashMessenger = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');
        $flashMessenger->setNamespace($namespace)->addMessage($message);
        
        $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('Redirector');
        $redirector->gotoUrlAndExit('/admin/user');
    }


}